<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\Util;

/**
 * 网络请求
 */
class Curl
{

    protected static $timeout = 10;

    public static function run ($url, $data, $isPost, $options)
    {
        $data && $isPost=true;

        // 统计 curl 数量
        @$GLOBALS['_KCSLOG_PROFILE_']['Curl']++;
        
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2882.4 Safari/537.36 KCDNS'); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, $options['TIMEOUT'] ?  : self::$timeout); // 设置超时限制
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, self::$timeout); // 连接超时
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);//302继续跳转
        if ($isPost)
        {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        }
        
        $startTime = microtime(true);
        $response = curl_exec($curl);
        $costTime = number_format(microtime(true) - $startTime, 3);
        $error = curl_errno($curl) and $error .= ' / ' . curl_error($curl);
        curl_close($curl);
        
        \KCSLog::DEBUG('[CURL] [URL]      : ' . $url);
        $isPost and \KCSLog::DEBUG('[CURL] [POST]     : ' . json_encode($data, JSON_UNESCAPED_UNICODE));
        \KCSLog::DEBUG('[CURL] [TIME]     : ' . $costTime . 's');
        \KCSLog::DEBUG('[CURL] [RESPONSE] : ' . $response . '');
        
        if ($error)
        {
            \KCSLog::WARN('[CURL] [ERROR]    : ' . $error);
            throw new \Exception($error);
        }
        
        return $response;
    }
}